package com.eralink.readerfinderlib;

import java.util.HashMap;

final class NetConfigParser {
    private final HashMap<String, String> fields = new HashMap<>();

    public NetConfigParser() {

    }

    public boolean parse(String net_config) {
        for ( String section : net_config.trim().split(";")) {
            String field = section.trim();
            if (field.isEmpty()) {
                continue;
            }
            final String[] pair = field.split("=");
            if (2 != pair.length) {
                return false;
            }

            fields.put(pair[0].trim(), pair[1].trim());
        }

        return true;
    }

    public boolean getValueByName(String key, final String[] value) {
        if (!fields.containsKey(key)) {
            return false;
        }

        value[0] = fields.get(key);

        return true;
    }

    public boolean validate() {
        final Integer dhcp = Utils.tryParseInt(fields.get("dhcp"));
        if (dhcp == null || 0 > dhcp || 1 < dhcp) {
            return false;
        }

        final String gateway = fields.get("gateway");
        final String mask = fields.get("mask");
        final String ip = fields.get("ip");
        final String port = fields.get("port");
        if (!Utils.ipCheck(gateway) || !Utils.ipCheck(mask) || !Utils.ipCheck(ip) || !Utils.isValidPort(port)) {
            return false;
        }

        final Integer baud = Utils.tryParseInt(fields.get("baud"));
        if (baud == null || 0 >= baud) {
            return false;
        }

        final Integer parity = Utils.tryParseInt(fields.get("parity"));
        if (parity == null || 0 > parity || 2 < parity) {
            return false;
        }

        final Integer databits = Utils.tryParseInt(fields.get("databits"));
        if (databits == null ||  5 > databits || 8 < databits) {
            return false;
        }

        final Integer stopbits = Utils.tryParseInt(fields.get("stopbits"));
        if (stopbits == null || 1 > stopbits || 2 < stopbits) {
            return false;
        }

        final String server_ip = fields.get("server_ip");
        if (server_ip != null) {
            final String server_port = fields.get("server_port");
            if (!Utils.ipCheck(server_ip) || !Utils.isValidPort(server_port)) {
                return false;
            }

            final Integer net_mode = Utils.tryParseInt(fields.get("net_mode"));
            if (net_mode == null || 0 > net_mode || 1 < net_mode) {
                return false;
            }

            final Integer product_code = Utils.tryParseInt(fields.get("product_code"));
            if (product_code == null) {
                return false;
            }
        }

        return true;
    }
}
